package com.iot.util;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class Common {

    // 后台访问
    public static final String BACKGROUND_PATH = "WEB-INF/jsp";
    // 前台访问
    public static final String WEB_PATH = "/WEB-INF/jsp/web";
    private final static ThreadLocal<SimpleDateFormat> timeFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };


    @SuppressWarnings("unchecked")
    public static Map<String, Object> FormMap(Object formMap) {
        return (Map<String, Object>) formMap;
    }

    /**
     * 判断变量是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (null == s || "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmpty(Object input) {
        if (input == null || "".equals(input))
            return true;
        String str = input.toString();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符串是否有值
     *
     * @param input
     * @return
     */
    public static boolean hasValue(String input) {
        return !isEmpty(input);
    }

    public static boolean hasValue(Object input) {
        return !isEmpty(input);
    }


    public static int toInt(String str, int defValue) {
        try {
            if (str.indexOf(".") > -1) {
                str = str.substring(0, str.indexOf("."));
            }
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    public static int toInt(Object obj, int defValue) {
        if (obj == null)
            return defValue;
        return toInt(obj.toString(), defValue);
    }


    public static float toFloat(String str, int defValue) {
        try {
            return Float.parseFloat(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    public static double toDouble(Object obj) {
        if (obj == null)
            return 0;
        return toDouble(obj.toString(), 0);
    }

    public static double toDouble(String str, int defValue) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    public static String formatDouble4(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(d);
    }

    /**
     * 如果只是用于程序中的格式化数值然后输出，那么这个方法还是挺方便的。
     * 应该是这样使用：System.out.println(String.format("%.2f", d));
     *
     * @param d
     * @return
     */
    public static String formatDouble(double d, int f) {

        return String.format("%." + f + "f", d);
    }


    public static float toFloat(Object obj) {
        if (obj == null)
            return 0;
        return toFloat(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 字符串转字符串null转""
     *
     * @param s
     * @return
     */
    public static String getString(String s) {
        return s == null ? "" : s;
    }

    /**
     * 对象转字符串
     *
     * @param s
     * @return
     */
    public static String getString(Object s) {
        return s == null ? "" : s.toString();
    }


    /**
     * 获取当前时间为每年第几周
     *
     * @return
     */
    public static int getWeekOfYear() {
        return getWeekOfYear(new Date());
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
        week = week == 0 ? 52 : week;
        return week > 0 ? week : 1;
    }

    public static boolean equals(String str1, String str2) {
        return str1.equals(str1);
    }

    /**
     * 日期格式字符串转短日期
     *
     * @param str
     * @return
     */
    public static Date toshortDate(String str) {
        Date date = null;
        try {
            if(!str.isEmpty()){
            date = dateFormater.get().parse(str);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 日期格式字符串转长日期
     *
     * @param str
     * @return
     */
    public static Date toLongDate(String str) {
        Date date = null;
        try {
            date = timeFormater.get().parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 日期转长字符串日期格式
     *
     * @param date
     * @return
     */
    public static String getLongDate(Date date) {
        return timeFormater.get().format(date);
    }

    /**
     * 日期转短字符串日期格式
     *
     * @param date
     * @return
     */
    public static String getShortDate(Date date) {
        return dateFormater.get().format(date);
    }

    public static String getLongDate(String date) {
        return timeFormater.get().format(date);
    }

    public static String getShortDate(String date) {
        return dateFormater.get().format(date);
    }

    /**
     * 得到当前时间
     *
     * @return
     */
    public static String getNowDateTime() {
        Date d = new Date();
        String dateNowStr = timeFormater.get().format(d);
        return dateNowStr;
    }

    /**
     * 得到当前日期
     *
     * @return
     */
    public static String getNowDate() {
        Date d = new Date();
        String dateNowStr = dateFormater.get().format(d);
        return dateNowStr;
    }


    public static String getNowTime() {
        Date d = new Date();
        String dateNowStr = timeFormater.get().format(d);
        return dateNowStr;
    }

    /**
     * 得到当前日期 年-月-01
     *
     * @return
     */
    public static String getNowYearMonth() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String mMonth = "";
        if (month < 10) {
            mMonth = "0" + month;
        } else
            mMonth = month + "";
        return year + "-" + mMonth + "-01";
    }

    /**
     * 得到当前日期 年
     *
     * @return
     */

    public static String getYear() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        return sdf.format(date);
    }

    /**
     * 得到当前日期 月
     *
     * @return
     */
    public static String getMonth() {
        Calendar cal = Calendar.getInstance();
        //int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String mMonth = "";
        if (month < 10) {
            mMonth = "0" + month;
        } else
            mMonth = month + "";
        return mMonth;
    }

    /**
     * 得到当前日期 日
     *
     * @return
     */
    public static String getDay() {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String mDay = "";
        if (day < 10) {
            mDay = "0" + day;
        } else
            mDay = day + "";
        return mDay;
    }

    public static Date getSomeDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }

    public static Date getSomeDay(String date, int day) {
        Date date2 = toshortDate(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date2);
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }

    public static String getWorkNo() {
        long time = System.currentTimeMillis();

        return "XT" + time;
    }

    /**
     * 指定日期后几天
     *
     * @param startDay 指定日期
     * @param count    天数
     * @return
     */
    public static String getAfterDay(String startDay, int count) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(startDay);
            Calendar cl = Calendar.getInstance();
            cl.setTime(date);
            cl.add(Calendar.DATE, count);
            return sdf.format(cl.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 指定日期前几天
     *
     * @param startDay 指定日期
     * @param count    天数
     * @return
     */
    public static String getBeforeDay(String startDay, int count) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(startDay);
            Calendar cl = Calendar.getInstance();
            cl.setTime(date);
            cl.set(Calendar.DATE, cl.get(Calendar.DATE) - count);
            return sdf.format(cl.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 得到日期差
     *
     * @return
     */
    public static long datediff(String date1, String date2, Dt dt) {
        Date dt1 = toLongDate(date1);
        Date dt2 = toLongDate(date2);
        long time = 0;
        Calendar calendar = null;
        switch (dt) {
            case DT_YEAR:
                calendar = Calendar.getInstance();
                calendar.setTime(dt1);
                time = calendar.get(Calendar.YEAR);
                calendar.setTime(dt2);
                return time - calendar.get(Calendar.YEAR);
            case DT_QUARTER:
                calendar = Calendar.getInstance();
                calendar.setTime(dt1);
                time = calendar.get(Calendar.YEAR) * 4;
                calendar.setTime(dt2);
                time -= calendar.get(Calendar.YEAR) * 4;
                calendar.setTime(dt1);
                time += calendar.get(Calendar.MONTH) / 4;
                calendar.setTime(dt2);
                return time - calendar.get(Calendar.MONTH) / 4;
            case DT_MONTH:
                calendar = Calendar.getInstance();
                calendar.setTime(dt1);
                time = calendar.get(Calendar.YEAR) * 12;
                calendar.setTime(dt2);
                time -= calendar.get(Calendar.YEAR) * 12;
                calendar.setTime(dt1);
                time += calendar.get(Calendar.MONTH);
                calendar.setTime(dt2);
                return time - calendar.get(Calendar.MONTH);
            case DT_WEEK:
                calendar = Calendar.getInstance();
                calendar.setTime(dt1);
                time = calendar.get(Calendar.YEAR) * 52;
                calendar.setTime(dt2);
                time -= calendar.get(Calendar.YEAR) * 52;
                calendar.setTime(dt1);
                time += calendar.get(Calendar.WEEK_OF_YEAR);
                calendar.setTime(dt2);
                return time - calendar.get(Calendar.WEEK_OF_YEAR);
            case DT_DAY:
                time = dt1.getTime() / 1000 / 60 / 60 / 24;
                return time - dt2.getTime() / 1000 / 60 / 60 / 24;
            case DT_HOUR:
                time = dt1.getTime() / 1000 / 60 / 60;
                return time - dt2.getTime() / 1000 / 60 / 60;
            case DT_MINUTE:
                time = dt1.getTime() / 1000 / 60;
                return time - dt2.getTime() / 1000 / 60;
            case DT_SECOND:
                time = dt1.getTime() / 1000;
                return time - dt2.getTime() / 1000;

        }
        return dt1.getTime() - dt2.getTime();
    }

    /**
     * 返回二个时间相差的分分钟数,如果一个为空，返回为0；
     *
     * @param startDate，比如08：09
     * @param endDate，如18：09
     * @return
     */
    public static boolean getFiveMinutesDiff(Date start, Date end) {
        // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-M-d HH:mm:ss");

      //  Date start = toLongDate(startDate.toString());
      //  Date end = toLongDate(endDate.toString());
        long cha = end.getTime() - start.getTime();
        if (cha <= 120000) {
            return true; //说明小于5分钟
        } else {
            return false;
        }
    }

    public enum Dt {
        DT_DEFULT, DT_YEAR, DT_QUARTER, DT_MONTH, DT_WEEK, DT_DAY, DT_HOUR, DT_MINUTE, DT_SECOND
    }

    public static String CreateFilePath(HttpServletRequest request, String ejPath, String sjPath, String fileName) throws Exception {
        try {
            String path = request.getSession().getServletContext().getRealPath("/") + "upload/";

            // 判断目录是否存在，不存在则创建目录
            File pFile = new File(path);
            if (!pFile.exists()) {
                pFile.mkdir();
            }
            path += ejPath;
            File pFile1 = new File(path);
            if (!pFile1.exists()) {
                pFile1.mkdir();
            }

            path+=sjPath;
            File userAccountFile = new File(path);
            if (!userAccountFile.exists()) {
                userAccountFile.mkdir();
            }
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + ext;
            String filePath = path + newFileName;
            return filePath;
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }
    /**
     * 获得一个UUID
     * @return String UUID
     */
    public static String getUUID(){
        String uuid = UUID.randomUUID().toString();
        //去掉“-”符号
        return uuid.replaceAll("-", "");
    }

    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @param format
     * @return
     */
    public static String timeStamp2Date(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }






}
